import MarkdownIt from "markdown-it";

export default function img_size_align(md: MarkdownIt) {
  md.core.ruler.push('image_size', function (state) {
    for (let token of state.tokens) {
      if (token.type !== 'inline') continue
      if (token.children && token.children.length > 0) {
        for (let subToken of token.children) {
          if (subToken.type === 'image') {
            const { attrs } = subToken
            if (!attrs) continue
            for (let item of attrs) {
              if (item[0] === 'src' && item[1]) {
                const [paramStr, hashStr] = item[1].split("#")
                const obj = new URLSearchParams(paramStr.split('?')[1])
                if (obj.size > 0) {
                  const width = obj.get('width')
                  const height = obj.get('height')
                  if (width) attrs.push(['width', width])
                  if (height) attrs.push(['height', height])
                }
                if (hashStr === 'right') {
                  attrs.push(['align', hashStr])
                } else if (hashStr === 'center') {
                  attrs.push(['style', `margin-left: calc((100% - ${obj.get('width')})/2)`])
                }
                break
              }
            }
          }
        }
      }
    }
  });
}